#include "HookKit.h"

#include <WinBase.h>
#include <TlHelp32.h>
#include <Psapi.h>

#include <stdlib.h>
#include <stdio.h>
#include <string>

#pragma comment(lib,"Psapi.lib")


char* HookKit::tolowerstr(char* str,unsigned max)
{
	char* temp = (char*)malloc(sizeof(char)*(strlen(str)+1));
	unsigned int i=0;
	for(i=0; *(str+i) != 0 && i <= max ; i++)
		*(temp+i)=tolower(*(str+i));
	*(temp+i)=0;
	return temp;
}

int HookKit::GetProcessInfo(char* name,PRO_INFO* out)
{
	HANDLE SnapShot_h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,NULL);
	if( NULL  == SnapShot_h )
		return HookKit_FAILED_1;

	PROCESSENTRY32  Entry32; 
	Entry32.dwSize = sizeof(Entry32);

	if( FALSE == Process32First(SnapShot_h,&Entry32) )
		return HookKit_FAILED_2;

	while(Process32Next(SnapShot_h,&Entry32))
	{
		char* str0 = tolowerstr(name, (unsigned int)strlen(name));
		char* str1 = tolowerstr(Entry32.szExeFile,(unsigned int)strlen(Entry32.szExeFile));

		int result = strcmp(str1,str0);
		free(str0);
		free(str1);

		if(result != 0)
			continue;

		HANDLE h = OpenProcess(PROCESS_ALL_ACCESS,FALSE,Entry32.th32ProcessID);
		if( NULL == h )
			return HookKit_FAILED_3;

		out->Pid = Entry32.th32ProcessID;
		out->handle = h;

		CloseHandle(SnapShot_h);
		return HookKit_OK;
	}
	CloseHandle(SnapShot_h);
	return HookKit_FAILED_4;
}

DWORD HookKit::GetThreadID(DWORD pid)
{
	if( pid == 0 )
		return 0;

	HANDLE snap_h =  CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,pid);
	THREADENTRY32 t32;
	t32.dwSize = sizeof(t32);

	for(Thread32First(snap_h,&t32);Thread32Next(snap_h,&t32);)
	{
		if(t32.th32OwnerProcessID != pid)
			continue;

		CloseHandle(snap_h);
		return t32.th32ThreadID;
	}
	CloseHandle(snap_h);
	return 0;
}

HMODULE HookKit::GetModule(HANDLE handle,char* ModuleName)
{
	HMODULE  hMod[1024]={0};    
	DWORD len = 0;
	EnumProcessModules(handle,hMod,sizeof(hMod),&len);
	DWORD times = len/sizeof(DWORD);

	for(DWORD i = 0; i < times ; i++)
	{
		char name[1024]={0};
		GetModuleBaseName(handle,hMod[i],name,sizeof(name));
		char* str1 =tolowerstr(name,(unsigned int)strlen(name));
		char* str2 =tolowerstr(ModuleName,(unsigned int)strlen(ModuleName));
		int result = strcmp(str1,str2);
		free(str1);
		free(str2);

		if(result == 0)
			return hMod[i];
	}
	return 0;
}

HANDLE HookKit::GetHandle(HWND hwnd)
{
	DWORD pid = 0;
	GetWindowThreadProcessId(hwnd,&pid);

	if(pid == 0)
		return NULL;

	return OpenProcess(PROCESS_ALL_ACCESS,FALSE,pid);
}